package algorithms.que13;


import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;



/**
 * @功能
 * @创建时间 2020/8/1
 */
public class Buffer implements Iterable{

    Stack<Character> front = new Stack<Character>(); // 光标前面的
    Stack<Character> after = new Stack<Character>(); // 光标后面的
    public int size(){ return front.size() + after.size(); }
    public void insert(char c){
        front.push(c);
    }
    public char delete(){
        char ans = front.pop();
        return ans;
    }
    public void left(int k){
        if(k>=front.size()) return;
        for(int i=0;i<k;i++)
            after.push(front.pop());
    }
    public void right(int k){
        if(k>after.size()) return;
        for(int i=0;i<k;i++)
            front.push(after.pop());
    }
    @Override
    public Iterator iterator() {
        // TODO Auto-generated method stub
        return new BufferIterator();
    }
    private class BufferIterator implements Iterator{


        Iterator<Character> it;
        public BufferIterator(){
            Stack<Character> afterTemp = after.copy();
            for(Character c:front)
                afterTemp.push(c);
            it = afterTemp.iterator();
        }
        @Override
        public boolean hasNext() {
            // TODO Auto-generated method stub
            return it.hasNext();
        }

        @Override
        public Character next() {
            // TODO Auto-generated method stub
            return it.next();
        }

        @Override
        public void remove() {
            // TODO Auto-generated method stub

        }

    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Buffer b = new Buffer();
        String s = "Hellow word!";
        for(int i=0;i<s.length();i++){
            b.insert(s.charAt(i));
        }
        for(Object c:b)
            StdOut.print(c);
        StdOut.println();
        b.left(6);
        b.delete();
        for(Object c:b)
            StdOut.print(c);
        StdOut.println();
        b.right(4);
        b.insert('l');
        for(Object c:b)
            StdOut.print(c);
        StdOut.println();
    }


}